/*
 * 文件名: OfflineMapActivity.java
 * 版    权：  Copyright DingliCom Tech. Co. Ltd. All Rights Reserved.
 * 描    述: [该类的简要描述]
 * 创建人: 黄广府
 * 创建时间:2012-5-31
 * 
 * 修改人：
 * 修改时间:
 * 修改内容：[修改内容]
 */
package com.dinglicom.walktourmap.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.baidu.mapapi.MKOLSearchRecord;
import com.baidu.mapapi.MKOLUpdateElement;
import com.baidu.mapapi.MKOfflineMap;
import com.baidu.mapapi.MKOfflineMapListener;
import com.dinglicom.walktourmap.Logger;
import com.dinglicom.walktourmap.R;
import com.dinglicom.walktourmap.WalktourApp;
import com.dinglicom.walktourmap.logic.adapter.OfflineMapAdapter;
import com.dinglicom.walktourmap.logic.adapter.QuickAdapter;
import com.dinglicom.walktourmap.logic.model.City;
import com.dinglicom.walktourmap.utils.BaseContactUtil;
import com.dinglicom.walktourmap.utils.HanziToPinyin;
import com.dinglicom.walktourmap.utils.StringUtil;

/**
 * [一句话功能简述]<BR>
 * [功能详细描述]
 * @author 黄广府
 * @version [WalkTour Client V100R001C03, 2012-5-31] 
 */
public class OfflineMapActivity extends QuickActivity implements
        OnClickListener, MKOfflineMapListener {
    
    private static String TAG = "OfflineMapActivity";
    
    private OfflineMapAdapter cityAdapter;
    
    private List<City> cityList;
    
    private Map<Integer, MKOLUpdateElement> updateElementHashMap;
    
    /**
     * 离线地图管理对象
     */
    private MKOfflineMap mkOfflineMap;
    
    private ArrayList<MKOLUpdateElement> updateElementList;
    
    /**
     * 下载地图按钮
     */
    private Button downMapBtn;
    
    public final static String ADD_DOWNLOAD_TASK = "add_download_task";;
    
    private DownloadReceiver downloadReceiver;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.offlinemap);
        mkOfflineMap = new MKOfflineMap();
        mkOfflineMap.init(WalktourApp.getContext().mMapManager, this);
        findView();
        initData();
        downloadReceiver = new DownloadReceiver();
        registerReceiver(downloadReceiver, new IntentFilter(
                ADD_DOWNLOAD_TASK));
    }
    
    /**
     * 初始化地图控件<BR>
     * [功能详细描述]
     */
    public void findView() {
        
        downMapBtn = (Button) findViewById(R.id.down_map_btn);
        downMapBtn.setOnClickListener(this);
    }
    
    /**
     * 初始化化数据<BR>
     * [功能详细描述]
     */
    public void initData() {
        //List<MKOLSearchRecord> offlineMapList = mkOfflineMap.getOfflineCityList();
        cityList = new ArrayList<City>();
/*        for (MKOLSearchRecord searchRecord : offlineMapList) {
            City city = new City();
            city.setName(searchRecord.cityName);
            city.setSize(searchRecord.size);
            city.setId(searchRecord.cityID);
            cityList.add(city);
        }*/
        updateElementList = mkOfflineMap.getAllUpdateInfo();
        updateElementHashMap = new HashMap<Integer, MKOLUpdateElement>();
        if(updateElementList != null){
            for (MKOLUpdateElement element : updateElementList) {
                updateElementHashMap.put(element.cityID, element);
                City city = new City();
                city.setName(element.cityName);
                city.setSize(element.size);
                city.setId(element.cityID);
                cityList.add(city);
            } 
        }else {
            updateElementList = new ArrayList<MKOLUpdateElement>();
        }

        cityAdapter = new OfflineMapAdapter(OfflineMapActivity.this, cityList,
                updateElementHashMap,mkOfflineMap);
        updateView(cityList);
    }
    
    private void generateSpellNameAndInitialName(City model) {
        HanziToPinyin htp = HanziToPinyin.getInstance();
        String splitName = null;
        // 计算显示名和转化成拼音的字符串
        if (!StringUtil.isNullOrEmpty(model.getName())) {
            splitName = htp.getPinyinWithWhitespace(model.getName());
            model.setSpellName(htp.getPinyin(model.getName()));
        }
        if (!StringUtil.isNullOrEmpty(splitName)) {
            StringBuffer sb = new StringBuffer();
            String[] str = splitName.split(" ");
            if (str != null) {
                for (int i = 0; i < str.length; i++) {
                    if (str[i].length() >= 1) {
                        sb.append(str[i].charAt(0));
                    }
                }
            }
            model.setInitialName(sb.toString());
            model.setSimplePinyin(sb.toString());
            Logger.d(TAG, model.toString());
            
        }
    }
    
    /**
     * 添加下载地图任务<BR>
     * [功能详细描述]
     * @author 黄广府
     * @version [WalkTour Client V100R001C03, 2012-6-4]
     */
    class DownloadReceiver extends BroadcastReceiver {
        
        /**
         * [一句话功能简述]<BR>
         * [功能详细描述]
         * @param context
         * @param intent
         * @see android.content.BroadcastReceiver#onReceive(android.content.Context, android.content.Intent)
         */
        @Override
        public void onReceive(Context context, Intent intent) {
            City city = (City) intent.getSerializableExtra("city");
            if(city != null){
                Logger.i(TAG, "cityId:" + city.getId());
                mkOfflineMap.start(city.getId()); 
            }
            cityList.add(city);
            MKOLUpdateElement element = new MKOLUpdateElement();
            element.cityID = city.getId();
            element.cityName = city.getName();
            element.status = MKOLUpdateElement.WAITING;
            element.ratio = 0;
            updateElementList.add(element);
            updateView(cityList);
/*            MKOLUpdateElement element = mkOfflineMap.getUpdateInfo(cityId);
            updateElementList.add(element);
            City city = new City();
            city.setName(element.cityName);
            city.setSize(element.size);
            city.setId(element.cityID);
            cityList.add(city);
            cityAdapter.notifyDataSetChanged();
            updateView(cityList);*/
        }
        
    }
    
    /**
     * [一句话功能简述]<BR>
     * [功能详细描述]
     * @return
     * @see com.dinglicom.walktourmap.ui.QuickActivity#getQuickAdapter()
     */
    @Override
    protected QuickAdapter getQuickAdapter() {
        return cityAdapter;
    }
    
    /**
     * [一句话功能简述]<BR>
     * [功能详细描述]
     * @param cityList
     * @return
     * @see com.dinglicom.walktourmap.ui.QuickActivity#generateDisplayList(java.util.List)
     */
    @SuppressWarnings("unchecked")
    @Override
    protected List<Object> generateDisplayList(List<?> cityList) {
        if (null != cityList) {
            List<City> list = (List<City>) cityList;
            for (City model : list) {
                if (null != model.getName()) {
                    this.generateSpellNameAndInitialName(model);
                }
            }
        }
        return BaseContactUtil.contactListForDisplay((List<? extends City>) cityList);
    }
    
    /**
     * 离线地图事件回调接口<BR>
     * [功能详细描述]
     * @param type 类型
     * @param state 状态
     * @see com.baidu.mapapi.MKOfflineMapListener#onGetOfflineMapState(int, int)
     */
    @Override
    public void onGetOfflineMapState(int type, int state) {
        Logger.e(TAG, "onGetOfflineMapState:" + "type:" + type + "    state:"
                + state);
        switch (type) {
            case MKOfflineMap.TYPE_DOWNLOAD_UPDATE:
                MKOLUpdateElement element = mkOfflineMap.getUpdateInfo(state);
                updateElementHashMap.put(element.cityID, element);
                Logger.e(TAG, "cityName:" + element.cityName + "    \n服务端数据大小:"
                        + element.serversize / 1024 / 1024 + "    \n百分比："
                        + element.ratio + "\n下载状态：" + element.status);
                Toast.makeText(OfflineMapActivity.this,
                        "cityName:" + element.cityName + "\n服务端数据大小:"
                                + element.serversize / 1024 / 1024 + "  \n百分比："
                                + element.ratio + "\n下载状态：" + element.status,
                        Toast.LENGTH_LONG).show();
                cityAdapter.notifyDataSetChanged();
                break;
            
            default:
                break;
        }
    }
    
    /**
     * [一句话功能简述]<BR>
     * [功能详细描述]
     * @param v
     * @see android.view.View.OnClickListener#onClick(android.view.View)
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.down_map_btn:
                Intent intent = new Intent(OfflineMapActivity.this,
                        DownloadMapActivity.class);
                startActivity(intent);
                break;
            
            default:
                break;
        }
        
    }
    
    /**
     * [一句话功能简述]<BR>
     * [功能详细描述]
     * @see android.app.Activity#onDestroy()
     */
    
    @Override
    protected void onDestroy() {
        //WalktourApp.getContext().mMapManager.stop();
        unregisterReceiver(downloadReceiver);
        super.onDestroy();
    }
    
    /**
     * [一句话功能简述]<BR>
     * [功能详细描述]
     * @see android.app.Activity#onResume()
     */
    
    @Override
    protected void onResume() {
        WalktourApp.getContext().mMapManager.start();
        super.onResume();
    }
    
}
